// actionCreator action生成器
// fetchTodoList = async () => {
//   // async 处理完异步之后，才把数据给了redux , 能不能让redux直接自己处理异步，自己拿到数据，组件只负责发送命令
//   const todos = await axios.get('/api/todo')
//   this.props.dispatch(actionCreator.getTodoList(todos.data.data))
// }
import axios from 'axios'
//
export const actionCreator = {
  // thunk中间件 可以让 action 变为函数
  getInitTodoList() {
    return async (dispatch) => {
      const todos = await axios.get('/api/todo')
      dispatch(this.getTodoList(todos.data.data))
    }
  },
  getTodoList(data) {
    return {
      type: 'init_todo_list',
      payload: data,
    }
  },
  getInputChangeValue(value) {
    return {
      type: 'input_change_value',
      payload: value,
    }
  },
  getAddTodoItem() {
    return {
      type: 'add_todo_item',
    }
  },
  getRemoveTodoItem(index) {
    return {
      type: 'remove_todo_item',
      payload: index,
    }
  },
}

// 提取异步代码
const defaultState = {
  list: [],
  value: '',
}

// reducer 是纯函数
export default (state = defaultState, action) => {
  // 1. 拷贝数据
  const newState = JSON.parse(JSON.stringify(state))
  // 初始化获取数据
  if (action.type === 'init_todo_list') {
    newState.list = action.payload
  }

  // 触发受控
  if (action.type === 'input_change_value') {
    newState.value = action.payload
  }

  // 添加数据
  if (action.type === 'add_todo_item') {
    newState.list = [...newState.list, { id: Date.now(), value: newState.value }]
    newState.value = ''
  }

  // 删除数据
  if (action.type === 'remove_todo_item') {
    newState.list.splice(action.payload, 1)
  }

  // cart逻辑

  // 登陆逻辑

  //

  return newState
}
